using MediatR;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Roles.Commands.DeleteRole;

public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, ApiResult<bool>>
{
  private readonly IUnitOfWork _unitOfWork;
  private readonly ILogger<DeleteRoleCommandHandler> _logger;

  public DeleteRoleCommandHandler(IUnitOfWork unitOfWork, ILogger<DeleteRoleCommandHandler> logger)
  {
    _unitOfWork = unitOfWork;
    _logger = logger;
  }

  public async Task<ApiResult<bool>> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
  {
    try
    {
      var role = await _unitOfWork.RoleRepository.GetRoleWithUsersAsync(request.Id);
      if (role == null)
        return ApiResult<bool>.Failure(404, "角色不存在");

      // 调用领域方法执行删除（内部会检查业务规则和添加领域事件）
      role.Delete();

      // 持久化变更
      await _unitOfWork.RoleRepository.RemoveAsync(role);
      await _unitOfWork.SaveChangesAsync();

      return ApiResult<bool>.Success(true, "角色删除成功");
    }
    catch (InvalidOperationException ex)
    {
      // 捕获领域规则抛出的异常
      _logger.LogWarning(ex, "删除角色违反业务规则");
      return ApiResult<bool>.Failure(400, ex.Message);
    }
    catch (Exception ex)
    {
      _logger.LogError(ex, "删除角色时发生错误");
      return ApiResult<bool>.Failure(500, "删除角色时发生错误");
    }
  }
}